<template>
  <div class="message-layout">
    <!-- 左侧侧边栏 -->
    <ChatSidebar 
      :user="currentUser" 
      :history-list="historyList"
      @select-history="handleHistorySelect"
      @delete-history="deleteHistory"
      @clear-history="clearHistory"
      @view-all="viewAllHistory"
      @replay="replayTask"
      @download="downloadReport"
      @download-all="downloadAllReports"
      @download-stats="downloadReportStats"
    />

    <!-- 主操作区 -->
    <main class="main-content">
      <!-- 顶部水印/Logo -->
      <div class="org-logo">
        <i class="fa-solid fa-building"></i> 中国联通软件研究院
      </div>

      <div class="welcome-card">
        <h1>欢迎使用智能软件测试助手</h1>
        <p class="subtitle">请输入您的测试任务需求，我们将为您提供专业的自动化测试服务。</p>

        <!-- 输入区域 -->
        <div class="input-area">
          <textarea 
            v-model="taskInput" 
            placeholder="例如：请帮我对登录模块进行功能测试，包含异常密码输入的场景..."
            @keydown.ctrl.enter="startTest"
            @keydown.meta.enter="startTest"
          ></textarea>

          <div class="action-buttons">
            <button class="btn btn-secondary" @click="importTestCases">
              <font-awesome-icon icon="upload" /> 导入用例
            </button>
            <button 
              class="btn btn-primary" 
              :disabled="!taskInput.trim() || isLoading"
              @click="startTest"
            >
              <font-awesome-icon v-if="isLoading" icon="spinner" spin />
              <font-awesome-icon v-else icon="paper-plane" />
              {{ isLoading ? '执行中...' : '开始测试' }}
            </button>
          </div>
        </div>

        <!-- 快捷提示词 -->
        <div class="tips">
          <span 
            v-for="tip in quickTips" 
            :key="tip" 
            class="tip-chip"
            @click="selectQuickTip(tip)"
          >
            {{ tip }}
          </span>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/modules/auth'
import { getHistoryRecords, clearAllHistoryRecords } from '@/services/history'
import { createConversation } from '@/services/conversation'
import ChatSidebar from '@/components/layout/ChatSidebar.vue'

// 路由和状态管理
const router = useRouter()
const authStore = useAuthStore()

// 当前用户信息
const currentUser = computed(() => authStore.user || {})

// 响应式数据
const taskInput = ref('')
const isLoading = ref(false)

interface HistoryItem {
  id: number | string;
  title: string;
  createdAt: Date;
  status: string;
}

const historyList = ref<HistoryItem[]>([])

// 快捷提示词
const quickTips = [
  '性能测试脚本生成',
  '接口自动化用例',
  'UI 回归测试',
  '功能测试用例设计',
  '百度搜索李白',
  '兼容性测试方案'
]

/**
 * 选择快捷提示词
 * @param tip 提示词内容
 */
const selectQuickTip = (tip: string) => {
  taskInput.value = tip
}

/**
 * 开始测试任务
 */
const startTest = async () => {
  console.log('startTest called')
  if (!taskInput.value.trim() || isLoading.value) return

  isLoading.value = true
  try {
    // 保存用户输入内容
    const userInput = taskInput.value.trim()
    console.log('Creating conversation with title:', userInput.substring(0, 50), 'and content:', userInput)
    
    // 创建对话
    const conversation = await createConversation(
      userInput.substring(0, 50), // 取前50个字符作为标题
      userInput
    )
    console.log('Conversation created:', conversation)

    // 清空输入框
    taskInput.value = ''

    // 跳转到聊天页面，并通过 URL query 传递 autoSend 参数
    // 我们不在这里 sendMessage，而是让 ChatPage 去发，这样用户能看到 loading 状态
    console.log('Navigating to chat-page with conversationId:', conversation.id, 'and autoSend:', userInput)
    router.push({
      path: '/chat-page',
      query: {
        conversationId: conversation.id,
        autoSend: userInput // 将用户输入的内容传递过去
      }
    })
    console.log('Navigation completed')

  } catch (error) {
    console.error('启动测试任务失败:', error)
  } finally {
    isLoading.value = false
    console.log('startTest finished')
  }
}

/**
 * 导入测试用例
 */
const importTestCases = () => {
  // 创建文件输入元素
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.json,.csv,.xlsx,.txt'
  input.onchange = (e) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (file) {
      console.log('导入文件:', file.name)
      // 这里可以处理文件导入逻辑
    }
  }
  input.click()
}

/**
 * 查看全部历史
 */
const viewAllHistory = () => {
  console.log('查看全部历史')
  // 可以跳转到历史记录页面
}

/**
 * 回放任务
 * @param item 历史记录项
 */
const replayTask = (item: any) => {
  console.log('回放任务:', item)
  // 实现回放逻辑
}

/**
 * 下载报告
 * @param item 历史记录项
 */
const downloadReport = (item: any) => {
  console.log('下载报告:', item)
  // 实现下载逻辑
}

/**
 * 删除历史记录
 * @param id 历史记录ID
 */
const deleteHistory = async (id: string) => {
  if (confirm('确定要删除这条历史记录吗？')) {
    try {
      // 实现删除逻辑
      historyList.value = historyList.value.filter(item => item.id !== id)
      console.log('删除历史记录:', id)
    } catch (error) {
      console.error('删除历史记录失败:', error)
      alert('删除历史记录失败，请重试')
    }
  }
}

/**
 * 处理历史记录选择
 * @param item 历史记录项
 */
const handleHistorySelect = (item: any) => {
  console.log('选择历史记录:', item)
  // 实现历史记录选择逻辑
}

/**
 * 下载全部报告
 */
const downloadAllReports = () => {
  console.log('下载全部报告')
  // 这里实现下载逻辑
}

/**
 * 下载报告统计
 */
const downloadReportStats = () => {
  console.log('下载报告统计')
  // 这里实现下载逻辑
}

/**
 * 清空历史
 */
const clearHistory = async () => {
  if (confirm('确定要清空所有历史记录吗？')) {
    try {
      await clearAllHistoryRecords()
      historyList.value = []
    } catch (error) {
      console.error('清空历史记录失败:', error)
      alert('清空历史记录失败，请重试')
    }
  }
}



/**
 * 组件挂载时加载历史记录
 */
onMounted(async () => {
  try {
    // 加载用户历史记录
    const records = await getHistoryRecords()
    historyList.value = records.map(record => ({
      id: record.id,
      title: record.title,
      createdAt: new Date(record.timestamp),
      status: record.status || 'completed'
    }))
  } catch (error) {
    console.error('加载历史记录失败:', error)
    // 如果获取失败，显示空状态
    // 添加一些模拟数据用于测试
    historyList.value = [
      {
        id: '1',
        title: '登录模块功能测试',
        createdAt: new Date(Date.now() - 3600000),
        status: 'completed'
      },
      {
        id: '2',
        title: '注册模块异常测试',
        createdAt: new Date(Date.now() - 7200000),
        status: 'failed'
      },
      {
        id: '3',
        title: '搜索功能性能测试',
        createdAt: new Date(Date.now() - 10800000),
        status: 'running'
      },
      {
        id: '4',
        title: '支付流程集成测试',
        createdAt: new Date(Date.now() - 14400000),
        status: 'interrupted'
      }
    ]
  }
})
</script>

<style scoped>
.message-layout {
  display: flex;
  height: 100vh;
  overflow: hidden;
  background-color: var(--bg-color, #f5f7fa);
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
  background-image: radial-gradient(rgba(230, 0, 39, 0.08) 1px, transparent 1px);
  background-size: 20px 20px;
}

.org-logo {
  position: absolute;
  top: 20px;
  right: 30px;
  font-weight: bold;
  color: var(--text-light, #666);
  display: flex;
  align-items: center;
  gap: 10px;
  opacity: 0.8;
}

.welcome-card {
  width: 100%;
  max-width: 800px;
  text-align: center;
  padding: 0 20px;
}

.welcome-card h1 {
  font-size: 2.5rem;
  color: var(--text-dark, #333);
  margin-bottom: 10px;
  font-weight: 700;
}

.welcome-card .subtitle {
  font-size: 1.1rem;
  color: var(--text-light, #666);
  margin-bottom: 40px;
}

.input-area {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  padding: 20px;
  border: 1px solid var(--border-color, #e0e0e0);
  transition: all 0.3s ease;
}

.input-area:focus-within {
  box-shadow: 0 6px 25px rgba(230, 0, 39, 0.15);
  border-color: var(--primary-color, #E60027);
}

textarea {
  width: 100%;
  height: 120px;
  border: none;
  resize: none;
  font-size: 16px;
  outline: none;
  color: var(--text-dark, #333);
  margin-bottom: 15px;
}

textarea::placeholder {
  color: #aaa;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  border-top: 1px solid #f5f5f5;
  padding-top: 16px;
}

.btn {
  padding: 10px 24px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid transparent;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-primary {
  background-color: var(--primary-color, #E60027);
  color: white;
  box-shadow: 0 4px 10px rgba(230, 0, 39, 0.3);
}

.btn-primary:hover:not(:disabled) {
  background-color: #c40022;
  transform: translateY(-1px);
}

.btn-primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.btn-secondary {
  background-color: white;
  border-color: var(--border-color, #e0e0e0);
  color: var(--text-dark, #333);
}

.btn-secondary:hover {
  background-color: #f8f8f8;
  border-color: #ccc;
}

.tips {
  margin-top: 30px;
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
}

.tip-chip {
  background: white;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 12px;
  color: var(--text-light, #666);
  border: 1px solid #eee;
  cursor: pointer;
  transition: all 0.3s;
}

.tip-chip:hover {
  border-color: var(--primary-color, #E60027);
  color: var(--primary-color, #E60027);
}
</style>
